<template>
  <div class="w-full">
    <div class="px-6 py-4 bg-white rounded-[6px] mb-6">
      <div class="text-default text-[18px] font-[400] flex items-center mb-1 leading-6">
        <span class="text-custom-text text-[18px] font-[400]">{{ paperData.name }}</span>
        <img class="pl-2" src="@/assets/images/star.png" alt="" v-for="item in paperData.level">
      </div>
      <div class="flex items-center">
        <div class="flex items-center mr-6 leading-[22px]">
          <span class="text-[#000]/45 text-[14px] font-[400]" @click="setPaperSubmit">考核名称：</span>
          <span class="text-[#000]/65 text-[14px] font-[400]">{{ paperData.name }}</span>
        </div>
        <div class="flex items-center mr-6 leading-[22px]">
          <span class="text-[#000]/45 text-[14px] font-[400]">总分：</span>
          <span class="text-[#000]/65 text-[14px] font-[400]">{{ paperData.total_score }}</span>
        </div>
        <div class="flex items-center mr-6 leading-[22px]">
          <span class="text-[#000]/45 text-[14px] font-[400]">建议时长：</span>
          <span class="text-[#000]/65 text-[14px] font-[400]">{{ paperData.duration }}分钟</span>
        </div>
        <div class="flex items-center leading-[22px]">
          <span class="text-[#000]/45 text-[14px] font-[400]">上次考核：</span>
          <span class="text-[#000]/65 text-[14px] font-[400]">{{ paperData.last_exam_time || '-' }}</span>
        </div>
      </div>
    </div>
    <div>
      <div class="control-panel">
        <span>操作提示：</span>
        <span>1、F11 打开全屏</span>
        <span>2、Alt + Tab 可唤起鼠标</span>
        <el-button @click="SendMessageToUnity('你好，这里是发送消息给Unity的示例')">
          点击发送消息给Unity</el-button>
      </div>
      <!-- <div ref="container" class="exe-container"></div> -->
      <div ref="container" class="exe-container">
        <iframe id="unityFrame" src="http://36.156.46.163:8089/training/unityframe-message-demo/" allowfullscreen="true" height="700" width="1000"
        title="Iframe Example"></iframe>
      </div>
      
    </div>
  </div>
</template>

<script setup>
// const { ipcRenderer } = require('electron');
import { ElMessage } from "element-plus";
import { examApi } from "@/api/index.js";
import { StorageUtil } from "@/utils/common.js";
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useRoute, useRouter } from "vue-router";
import dayjs from 'dayjs';

const route = useRoute();
const router = useRouter();
const questionData = ref([]);
const testId = ref('');
const container = ref(null);

// 定义 WebSocket 实例
const socket = ref(null);

const paperData = computed(() => {
  return StorageUtil.session.get('paperData');
});

const handleExeStartFailed = (event, errorMessage) => {
  ElMessage.error(`程序启动失败: ${errorMessage}`);
};

const targetWindowHandle = ref(null); // 添加这行来存储窗口句柄

// 修改 handleExeEmbedded 函数来接收窗口句柄
const handleExeEmbedded = (event, data) => {
  const { ip, handle } = data;
  targetWindowHandle.value = handle; // 只保存窗口句柄
  isFullscreen.value = false; // 确保初始状态为非全屏
  connectWebSocket(ip);
};

const handleWsMessage = (event, message) => {
  handleWebSocketMessage(message);
};

// 添加全屏状态控制
const isFullscreen = ref(false);

// 修改 toggleFullScreen 方法
const toggleFullScreen = () => {
  if (!targetWindowHandle.value) {
    ElMessage.warning('窗口未准备就绪');
    return;
  }
  
  ipcRenderer.send('toggle-fullscreen', {
    isFullscreen: !isFullscreen.value,
    handle: targetWindowHandle.value
  });
  
};

// 修改处理函数，添加 F11 处理
const handleKeyPress = (event) => {
  // 如果目标是嵌入的 exe 窗口，阻止事件冒泡
  if (event.target.closest('.exe-container')) {
    // 允许事件继续传播到 exe
    return;
  }

  // 其他按键处理逻辑
  if (event.key === 'F11' && targetWindowHandle.value) {
    toggleFullScreen();
    event.preventDefault();
    event.stopPropagation();
  }
  if (event.key === 'Escape' && isFullscreen.value) {
    toggleFullScreen();
    event.preventDefault();
    event.stopPropagation();
  }
};

// 修改事件监听器的注册和移除方式
const eventHandlers = {
  'exe-start-failed': handleExeStartFailed,
  'exe-embedded': handleExeEmbedded,
  'ws-message': handleWsMessage,
  'fullscreen-toggled': (event, state) => {
    isFullscreen.value = state;
    // 添加或移除全屏样式类
    const container = document.querySelector('.exe-container');
    if (container) {
      container.classList.toggle('fullscreen', state);
    }
    if (!state) {
      // 退出全屏时显示提示
      ElMessage({
        message: 'Alt + Tab 唤起鼠标',
        type: 'info',
        duration: 3000
      });
    }
  },
  'escape-pressed': () => {
    if (isFullscreen.value) {
      toggleFullScreen();
    }
  },
  'f11-pressed': () => {
    if (!isFullscreen.value) {
      toggleFullScreen();
    }
  }
};

const SendMessageToUnity = (message) => {
            var unityWindow = document.getElementById("unityFrame", "*").contentWindow;
            unityWindow.postMessage(message, "*");
        }

onMounted(() => {
  getQuestionList();
  window.addEventListener("message", function (event) {
            console.log(event.data);
        })
  // 注册所有事件监听器
  // Object.entries(eventHandlers).forEach(([event, handler]) => {
  //   ipcRenderer.on(event, handler);
  // });
  // window.addEventListener('keydown', handleKeyPress, true); // 添加 true 表示在捕获阶段处理
  // window.addEventListener('keyup', handleKeyPress);
  // // 添加容器点击事件，确保 exe 窗口获得焦点
  // container.value.addEventListener('click', () => {
  //   if (targetWindowHandle.value) {
  //     ipcRenderer.send('focus-exe-window', targetWindowHandle.value);
  //   }
  // });
});

onUnmounted(() => {
  // 移除所有事件监听器
  Object.entries(eventHandlers).forEach(([event, handler]) => {
    ipcRenderer.removeListener(event, handler);
  });
  window.removeEventListener('keydown', handleKeyPress, true);
  window.removeEventListener('keyup', handleKeyPress);
  
  // 移除 WebSocket 事件监听器
  if (socket.value) {
    socket.value.close();
    socket.value = null;
  }
  
  // 发送关闭 exe 的消息
  ipcRenderer.send('close-exe');
});

// 连接 WebSocket 服务器
const connectWebSocket = (ip) => {
  socket.value = new WebSocket(`ws://${ip}:7133`);
};

// 发送消息
const sendMessage = (data) => {
  // 发送消息到主进程
  ipcRenderer.send('send-ws-message', data);
};

// 处理 WebSocket 消息
const handleWebSocketMessage = (message) => {
  console.log(message, 'WebSocket 消息2');
  // 在这里处理 WebSocket 消息
  if (message.Name === "NotifyBeginTraining") {
    setPaperStart();
  }else if (message.Name === "NotifyEndTraining") {
    sendMessage({"Name": "ClientQuit"})
  }else if (!!message.training_id) {
    setPaperSubmit(message)
  }
};

const setPaperStart = () => {
  const { paperId, chapterId } = route.query;
  const params = {
    paper: paperId,
    chapter: chapterId
  };
  examApi.setPaperStart(params).then(res => {
    testId.value = res;
  });
};

// 获取试题
const getQuestionList = () => {
  const { paperId, chapterId } = route.query;
  examApi.getQuestionList(paperId, chapterId).then(res => {
    questionData.value = res;
    this.SendMessageToUnity()
    // const { width, height } = container.value.getBoundingClientRect();
    // // 启动 exe 程序的方法
    // ipcRenderer.send('start-exe', width, height);
  });
};

// 提交考核
const setPaperSubmit = (data) => {
  const { paperId, chapterId } = route.query;
  const params = {
    paper: paperId,
    chapter: chapterId,
    test_id: testId.value,
    ...data
  };
  params['start_time'] = dayjs(params.start_time).format('YYYY-MM-DD HH:mm:ss')
  params['finish_time'] = dayjs(params.finish_time).format('YYYY-MM-DD HH:mm:ss')
  examApi.setPaperSubmit(params).then(res => {
    console.log(res, '提交结果')
    //提交结果. -1: 考核失败；1: 全部完成； 0: 下一关
    StorageUtil.session.set('assessResultData', res);
    const path = res.status == -1 ? '/examCourses/failfullLevel' : res.status == 1 ? '/examCourses/assesseEnd' : '/examCourses/successfulLevel';
    router.push({
      path,
      query: {
        paperId,
        chapterId,
        testId: testId.value
      }
    });
  });
};

</script>
<style scoped>
.control-panel {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  gap: 10px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 5px 10px;
  border-radius: 4px;
}

.alt-tip {
  color: #666;
  font-size: 14px;
}

.exe-container {
  width: 100%;
  height: 600px;
  transition: all 0.3s;
}
</style>